package client_commands

import scala.actors.Actor
import scala.actors.Actor._
import scala.actors.remote.Node
import scala.actors.remote.RemoteActor
import scala.actors.remote.RemoteActor._
import objects._
import executors.NewFileExecutor
import db.Client
import client_updater.ClientsUpdater
import client_updater.Update
import client_updater.FileUpdate

/**
 * Listens to updates about files that were added to a client's dropbox.<br>
 * Works as a remote actor that listens to messages on a given port.<br>
 * @param - port to listen on.<br>
 * @param - executor : Actor
 */
class NewFileActor(port: Int, executor : Actor) extends Actor {

  /**
   * The acting method of the actor.<br>
   * Receives messages about files that were added to a client's dropbox and then sends <br>
   * the information forwards to be processed against the data-base, the disk, and other clients. 
   */
  def act() {
    alive(port)
    register('NewFile, self)

    loop {
      react {
        case (uid : Long, cid : Long, name : String, parent : Long, size : Long, code : Long) =>
          {
            val receivedFile = new File2(uid ,cid ,name ,parent ,size ,code)
            println("Processing new file "+name)
            var result = (executor !? receivedFile)
            if (result == false) {
              var client = new Client
              client.setUserID(receivedFile.uid)
              client.setClientID(receivedFile.cid)
              ClientsUpdater.addUpdate(receivedFile.cid, new FileUpdate(
                "upload", receivedFile.name, receivedFile.parent, code))
            }
          }
        case "Quit" => {
          println("NewFileActor stopped")
          executor ! "Quit"
          exit()
        }
        case _ =>
          println("NewFileActor received unknown message")
      }
    }

  }

}

